package com.kaizen.server.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.handler.timeout.ReadTimeoutException;

import java.util.concurrent.TimeUnit;

public class ReadTimeoutHandler extends IdleStateHandler {

    private boolean closed;

    public ReadTimeoutHandler(int timeoutSeconds) {
        this(timeoutSeconds, TimeUnit.SECONDS);
    }

    /**
     * 未读时间 构造
     * @param timeoutSeconds
     * @param timeUnit
     */
    public ReadTimeoutHandler(int timeoutSeconds, TimeUnit timeUnit) {
        super(timeoutSeconds, 0 , 0, timeUnit);
    }

    protected void readTimeout(ChannelHandlerContext ctx) {
        if (!closed) {
            // 抛出读超时异常，并关闭Channel
            ctx.fireExceptionCaught(ReadTimeoutException.INSTANCE);
            ctx.close();
            closed = true;
        }

    }
}
